package com.hlkj.baojin.controller;

import com.hlkj.baojin.dao.ISoketDataDao;
import com.hlkj.baojin.entity.PasswordSet;
import com.hlkj.baojin.entity.SoketDataA;
import com.hlkj.baojin.entity.User;
import com.hlkj.baojin.entity.dto.CompanyDto;
import com.hlkj.baojin.jwt.JwtAuthenticationRequest;
import com.hlkj.baojin.jwt.JwtAuthenticationResponse;
import com.hlkj.baojin.service.AuthService;
import com.hlkj.baojin.service.CompanyService;
import com.hlkj.baojin.service.IUserService;
import com.hlkj.baojin.utils.bean.JsonResult;
import com.hlkj.baojin.utils.http.IpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author lzx
 */
@Api(value = "/bjjk", description = "权限管理")
@RestController
public class AuthController {
    @Value("${jwt.header}")
    private String tokenHeader;
    @Autowired
    private IUserService userService;
    private final AuthService authService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    public AuthController(AuthService authService) {
        this.authService = authService;
    }

    @ApiOperation(value = "用户登录", tags = {"权限管理"})
    @ApiResponse(code = 200, message = "成功,携带token及部分数据", response = JwtAuthenticationResponse.class)
    @PostMapping(value = "/auth/login")
    public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtAuthenticationRequest jwt, HttpServletRequest servletRequest) {
        // Return the token
        String tpken = authService.login(jwt.getUsername(), jwt.getPassword(), IpUtil.getIpAddr(servletRequest));
        User user = userService.getByUsername(jwt.getUsername());
        String name;
        if(user.getType().equals(2)) {
            name = "管理员";
        } else {
            CompanyDto companyDto = companyService.findCompanyById(user.getDeptId());
            name = companyDto.getName();
        }
        return ResponseEntity.ok(JsonResult.success(new JwtAuthenticationResponse(tpken, user.getType(), name,user.getId())));
    }

    @ApiOperation(value = "获取验证码", tags = {"权限管理"})
    @ApiResponse(code = 200, message = "成功", response = void.class)
    @GetMapping(value = "/auth/getCode/{username}")
    public ResponseEntity<?> getCode(@PathVariable("username") String username) {
        authService.getCode(username);
        return ResponseEntity.ok(JsonResult.success());
    }

    @ApiOperation(value = "忘记密码", tags = {"权限管理"})
    @ApiResponse(code = 200, message = "成功", response = void.class)
    @PostMapping(value = "/auth/passwordSet")
    public ResponseEntity<?> forgetPassword(@RequestBody PasswordSet passwordSet) {
        authService.forgetPassword(passwordSet);
        return ResponseEntity.ok(JsonResult.success());
    }

    @ApiOperation(value = "原密码验证", tags = {"权限管理"})
    @ApiResponse(code = 200, message = "成功", response = Boolean.class)
    @PostMapping(value = "/auth/vadicatePassword/{password}")
    public ResponseEntity<?> vadicatePassword(@PathVariable("password") String password) {
        return ResponseEntity.ok(JsonResult.success(authService.vadicate(password)));
    }

    @ApiOperation(value = "密码重置", tags = {"权限管理"})
    @ApiResponse(code = 200, message = "成功", response = void.class)
    @PostMapping(value = "/auth/passwordReset")
    public ResponseEntity<?> passwordSet(@RequestBody PasswordSet passwordSet) {
        authService.resetPassword(passwordSet);
        return ResponseEntity.ok(JsonResult.success());
    }

    @ApiOperation(value = "用户token刷新", tags = {"权限管理"})
    @ApiResponse(code = 200, message = "返回新token 且 old token disable", response = JwtAuthenticationResponse.class)
    //当前用户必须拥有User权限才能访问 否则 403
    @PostAuthorize("hasRole('ROLE_USER')")
    @PostMapping(value = "/refresh")
    public ResponseEntity<?> refreshAndGetAuthenticationToken(HttpServletRequest request) {
        String refreshedToken = authService.refresh(request.getHeader(tokenHeader));
        if (refreshedToken == null) {
            return ResponseEntity.badRequest().body(null);
        } else {
            return ResponseEntity.ok(JsonResult.success(new JwtAuthenticationResponse(refreshedToken)));
        }
    }

    @ApiOperation(value = "用户注册，开放接口", tags = {"权限管理"})
    @ApiResponse(code = 200, message = "返回新token 且 old token disable", response = JwtAuthenticationResponse.class)
    @RequestMapping(value = "/auth/register", method = RequestMethod.POST)
    public ResponseEntity<?> register(@RequestBody User addedUser) {
        authService.register(addedUser);
        return ResponseEntity.ok(null);
    }


}